package com.oraycn.esbasic.views.chatView;

import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.widget.AbsListView;
import android.widget.ListView;

import com.oraycn.esbasic.R;

import java.util.LinkedList;
import java.util.List;
import java.util.function.Predicate;

public class ChatBox extends ListView {

    //region Ctor
    public ChatBox(Context context) {
        super(context);
    }

    public ChatBox(Context context, AttributeSet attrs) {
        this(context, attrs, R.style.ChatBox);
    }

    public ChatBox(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public ChatBox(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }
    //endregion

    private ChatLVAdapter mLvAdapter;
    private LinkedList<ChatInfo> infos = new LinkedList<ChatInfo>();
    private Handler mHandler = new Handler();

    public void initialize(IChatDataProvider chatDataProvider) {
        this.mLvAdapter = new ChatLVAdapter(getContext(), infos, this,chatDataProvider);
        this.setAdapter(this.mLvAdapter);
    }

    public void addChatInfo(List<ChatInfo> chatInfos) {
        this.infos.addAll(chatInfos);
        this.mLvAdapter.notifyDataSetChanged();
    }

    public void addChatInfo(ChatInfo chatInfo) {
        this.infos.add(chatInfo);
        this.mLvAdapter.notifyDataSetChanged();
    }

    public void removeChatInfo(final String guid) {
        for (ChatInfo chatInfo : this.infos) {
            if (chatInfo.Guid.equals(guid)) {
                this.infos.remove(chatInfo);
                this.mLvAdapter.notifyDataSetChanged();
                break;
            }
        }
    }

    public void clear() {
        this.infos.clear();
        this.mLvAdapter.notifyDataSetChanged();
    }

    private void scrollToBottom()
    {
        this.setSelection(AbsListView.FOCUS_DOWN);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                setSelection(getBottom());
            }
        },200);
    }
}
